package com.xinsmartsky.penmaji.penmaji;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.xinsmartsky.penmaji.NewGridView.NewGridView;
import com.xinsmartsky.penmaji.SerialPort.FileOperation;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;

/*网格绘制*/
public class DrawActivity extends Activity implements AdapterView.OnItemSelectedListener, View.OnClickListener {
    private Spinner draw_spi_dz;
    private ArrayAdapter<String> adapter;
    private String[] str = new String[]{"点阵", "24 X 24", "32 X 32"};
    private LinearLayout draw_lin_gridview;
    private int MatLastNum = 0;//最后设置的矩阵个数
    private HorizontalScrollView draw_hs_gview;
    private int height;
    private Button draw_btn_dele = null;//清屏
    private Button draw_btn_send;
    private FileOperation fileOperation = new FileOperation();
    private Button draw_btn_save;
    private int devfd = -1;
    private String filename = "";
    private int drawingnum;//字条
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_draw);
        filename = getIntent().getStringExtra("filename");
        FindViewById();
        setOnClickListener();
        //打印预览
        if((filename)!= null){
            Drawing();
        }else{
            drawingnum = getIntent().getIntExtra("num", 0);
            devfd = getIntent().getIntExtra("fd", 0);
            Log.i("fd", "fd-------------------------------------" + devfd);
            MatLastNum = 24;
            lin_drawview();
        }
    }

    private NewGridView gridView;
    byte[] content;
    private void Drawing(){
        content = fileOperation.ReadDataFromFile(filename);
        MatLastNum = (content.length * 8) / 120;
        Log.i("ccc", "点阵=============" + MatLastNum);
        lin_drawview();
    }

    private void FindViewById() {
        draw_spi_dz = (Spinner) findViewById(R.id.draw_spi_dz);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, str);
        draw_lin_gridview = (LinearLayout) findViewById(R.id.draw_lin_gridview);
        draw_hs_gview = (HorizontalScrollView) findViewById(R.id.draw_hs_gview);
        draw_btn_dele = (Button) findViewById(R.id.draw_btn_dele);
        draw_btn_send = (Button) findViewById(R.id.draw_btn_send);
        draw_btn_save = (Button) findViewById(R.id.draw_btn_save);
        ((Button)findViewById(R.id.draw_btn_show)).setOnClickListener(this);
    }

    private void setOnClickListener() {
        draw_lin_gridview.setOnClickListener(this);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        draw_spi_dz.setAdapter(adapter);
        draw_spi_dz.setOnItemSelectedListener(this);
        draw_btn_dele.setOnClickListener(this);
        draw_btn_send.setOnClickListener(this);
        draw_btn_save.setOnClickListener(this);
    }

    private void lin_drawview() {
        if (draw_lin_gridview.getChildCount() > 0) {
            draw_lin_gridview.removeAllViews();
        }
        for (int i = 0; i < 1; i++) {
            draw_lin_gridview.addView(DrawGridView());
        }
    }

    boolean flagg = true;

    /*画网格布局*/
    private View DrawGridView() {
        final NewGridView draw_ngv_newview;
        final Button ditem_btn_eraser;//删除
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, 5, 0, 0);
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.activity_draw_item, null);//子布局
        draw_ngv_newview = (NewGridView) view.findViewById(R.id.draw_ngv_newview);//子布局中的控件
        ditem_btn_eraser = (Button) view.findViewById(R.id.ditem_btn_eraser);
        ditem_btn_eraser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                draw_ngv_newview.eraser();

            }
        });
        //触屏时设置不滑动
        draw_ngv_newview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    draw_hs_gview.requestDisallowInterceptTouchEvent(false);
                } else {
                    draw_hs_gview.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });
        if(MatLastNum == 32){
            lp.width = 5680;//32*120 的宽度
        }
        ViewTreeObserver vto = draw_ngv_newview.getViewTreeObserver();
        Log.i("vvv", "1111111111111111111111111" + "  ===== " + vto);
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Log.i("vvv", "222222222222222222222222222");
                draw_ngv_newview.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                height = draw_ngv_newview.getHeight();
                float fheight = (float) (height / (float) MatLastNum);
                draw_ngv_newview.setLength(fheight);
            }
        });
        draw_hs_gview.requestDisallowInterceptTouchEvent(false);
        draw_ngv_newview.setPort_num(MatLastNum);
        draw_ngv_newview.setHOR_num(120);//3列一组
        ////////////////
        ///////////////
        Log.i("vvv", "33333333333333333");
        view.setLayoutParams(lp);
        return view;
    }

    //设置spinner中的字体
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        TextView tv = (TextView) view;
        tv.setTextSize(30.0f);
        tv.setGravity(Gravity.CENTER_HORIZONTAL);//设置居中
        switch (position) {
            case 0: {
                break;
            }
            case 1: {
                MatLastNum = 24;
                lin_drawview();

                break;
            }
            case 2: {
                MatLastNum = 32;
                lin_drawview();
                break;
            }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    byte DrawArray[] = new byte[MatLastNum * 120 / 8];

//    NewGridView gridView = (NewGridView) (draw_lin_gridview.getChildAt(0)).findViewById(R.id.draw_ngv_newview);

    private void WriteArrayToFile(){
        NewGridView gridView = (NewGridView) (draw_lin_gridview.getChildAt(0)).findViewById(R.id.draw_ngv_newview);
        int practicelen = 0;
        //获取数组
        DrawArray = gridView.getDrawArray(MatLastNum);
        //图形长度：将长度放在第一个字节
        for(int i = 0; i < DrawArray.length; i++){
            if(DrawArray[i] != 0){
                practicelen = (i / (3 * (MatLastNum/8)) + 1);
            }
        }

        int type = 0 ;//表示图标
        if(MatLastNum == 24){
            type = 2;
        }else if(MatLastNum == 32){
            type = 3;
        }else {
            Log.i("fd", "dianzhennum error!");
        }
//                String dianzhen = Integer.toHexString(MatLastNum);
//                start_serialport.SetDataToAddress(0x08ed, (dianzhen.getBytes()[0]));//倒字
        fileOperation.SetArrayToAddress(type, drawingnum, DrawArray, practicelen);//向文件中写入信息
    }
    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            //向串口发送数据
            case R.id.draw_btn_send: {
                SerialPortActivity start_serialport = new SerialPortActivity();
                WriteArrayToFile();
                //遍历出字条的实际长度
                start_serialport.SendDataBlock(devfd);
                fileOperation.PrintData();
                break;
            }
            //保存成文件
            case R.id.draw_btn_save:{
                CreatDialog();
                break;
            }
            case R.id.draw_btn_show:{
                gridView = new NewGridView(DrawActivity.this);
                gridView.DrawingShow(content, MatLastNum, draw_lin_gridview);
                break;
            }
            case R.id.draw_btn_dele:{
                draw_lin_gridview.removeViewAt(0);//删除最后一个有汉字的
                //将数组置0
                Arrays.fill(DrawArray, (byte) 0);
                draw_lin_gridview.addView(DrawGridView());
                break;
            }
        }
    }

//保存文件的对话框
    private void CreatDialog(){
        //没有被载入或想要动态载入 与 findViewById不同
        AlertDialog.Builder builder = new AlertDialog.Builder(DrawActivity.this);
        LayoutInflater inflater = LayoutInflater.from(this);
        final View FileSaveView = inflater.inflate(R.layout.activity_draw_dialog, null);
        builder.setTitle("请输入文件名");
        builder.setView(FileSaveView);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String filename = "";
                EditText edtfilename = (EditText) FileSaveView.findViewById(R.id.drawdia_edt_fname);
                filename = edtfilename.getText().toString();
                SaveFile(filename);
            }
        });
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                                        int whichButton) {
                    }
                });
        builder.create().show();
    }

    private void showDialog(String str) {
        new AlertDialog.Builder(DrawActivity.this).setMessage(str)
                .show();
    }

    private void SaveFile(String filename){
        //获取数组
        NewGridView gridView = (NewGridView) (draw_lin_gridview.getChildAt(0)).findViewById(R.id.draw_ngv_newview);
        DrawArray = gridView.getDrawArray(MatLastNum);

        Log.i("ccc", "1==============" + DrawArray.length);
        //图形长度：将长度放在第一个字节
        try {
            if(fileOperation.CreateFile(filename)){
                //文件创建成功 将数据写入文件
                fileOperation.WriteDataToFile(DrawArray, filename);
                showDialog("保存文件成功！");
            }else {
                showDialog("保存文件失败，请重新命名...");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
